package com.hejia.bulbul.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.alibaba.fastjson.JSONObject;
import com.hejia.alauda.entity.FinancialAsset;
import com.hejia.alauda.entity.Presell;
import com.hejia.alauda.entity.ProductType;
import com.hejia.alauda.entity.ProductTypeField;
import com.hejia.alauda.entity.ProductTypeValue;
import com.hejia.alauda.entity.SaleActivity;
import com.hejia.alauda.entity.example.PresellExample;
import com.hejia.alauda.service.BalanceAndFinancingService;
import com.hejia.alauda.service.PresellService;
import com.hejia.alauda.service.ProductService;
import com.hejia.alauda.service.SaleActivityService;
import com.hejia.alauda.utils.Pager;
import com.hejia.bulbul.entity.DataTablesReturnObject;
import com.hejia.bulbul.entity.JSONParam;

@Controller
@RequestMapping("presell")
public class PresellController extends BaseController {

	@Resource
	private PresellService presellService;

	@Resource
	private ProductService productTypeService;

	@Resource
	private SaleActivityService saleActivityService;

	@Resource
	private BalanceAndFinancingService financialAssetService;

	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String presellList(Pager<Presell> pager, ModelMap model) {
		Pager<Presell> presells = presellService.findAllPresell(pager);
		model.put("presells", presells);
		return "/product/presell/presell_list";
	}

	/**
	 * 跳转到添加界面
	 */
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String addPresellList(ModelMap model) {

		// 获取产品分类列表
		List<ProductType> ptList = productTypeService.listProductType(null)
				.getList();
		// 获取活动
		List<SaleActivity> saList = saleActivityService.effectiveActivity();
		// 获取金融资产库存
		List<FinancialAsset> financialAssets = financialAssetService
				.findFinancialAssetInventory();

		model.put("productTypeList", ptList);
		model.put("saleActivityList", saList);
		model.put("financialAssets", financialAssets);

		return "/product/presell/presell_input";
	}

	/**
	 * 添加完保存
	 */
	@RequestMapping(value = "add", method = RequestMethod.POST)
	public String savePresellList(Long typeId, Presell presell, ModelMap model,
			RedirectAttributes redirectAttributes) {

		ProductType pt = productTypeService.getProductTypeById(typeId);
		presell.setProducttype(pt);

		if (presellService.savePresell(presell)) {
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", "排期预售添加成功");
		} else {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "排期预售添加失败");
		}

		return "redirect:/presell/list";
	}

	/**
	 * 跳转到修改界面
	 */
	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updatePresellList(@PathVariable Long id, ModelMap model) {
		Presell presell = presellService.getPresellById(id);
		if (presell.getProducttype() != null) {
			setProductTypeValue2Model(presell.getId(), presell.getProducttype()
					.getId(), "productTypeValue", model);
		}

		// 获取产品分类列表
		List<ProductType> ptList = productTypeService.listProductType(null)
				.getList();

		// 获取活动
		List<SaleActivity> saList = saleActivityService.effectiveActivity();

		model.put("saleActivityList", saList);
		model.put("productTypeList", ptList);
		model.put("presell", presell);
		return "/product/presell/presell_input";
	}

	/**
	 * 修改完保存
	 */
	@RequestMapping(value = "update/{id}", method = RequestMethod.POST)
	public String saveUpdatePresellList(Long typeId, @PathVariable Long id,
			Presell presell, RedirectAttributes redirectAttributes) {

		Presell presell2 = presellService.getPresellById(id);
		presell2.setModifyDate(new Date());
		presell2.setName(presell.getName());
		presell2.setTerm(presell.getTerm());
		presell2.setCategory(presell.getCategory());
		presell2.setActivitys(presell.getActivitys());
		if (presell.getRookie() == null) {
			presell2.setRookie(false);
		} else {
			presell2.setRookie(presell.getRookie());
		}

		ProductType pt = productTypeService.getProductTypeById(typeId);
		presell2.setProducttype(pt);

		if (presellService.modifyPresell(presell2)) {
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", "排期预售修改成功");
		} else {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "排期预售修改失败");
		}

		return "redirect:/presell/list";
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
	public String deletePresellList(@PathVariable Long id,
			RedirectAttributes redirectAttributes) {
		if (presellService.deletePresell(id)) {
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", "排期预售删除成功");
		} else {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "排期预售删除失败");
		}

		return "redirect:/presell/list";
	}

	/**
	 * 以ajax格式返回列表请求
	 *
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "presellAsAjax", method = RequestMethod.POST)
	@ResponseBody
	public DataTablesReturnObject<Presell> presellAsAjax(
			@RequestBody JSONParam[] params) {
		HashMap<String, String> paramMap = JSONParam.convertToMap(params);

		// 分页信息
		Pager<Presell> pager = new Pager<Presell>();
		int start = Integer.parseInt(paramMap.get("iDisplayStart"));
		int length = Integer.parseInt(paramMap.get("iDisplayLength"));
		pager.setPageSize(length);
		pager.setPageNumber(start / length + 1);

		// 查询条件
		PresellExample exp = new PresellExample();

		String sSearch = paramMap.get("sSearch");
		if (StringUtils.isNotEmpty(sSearch)) {
			exp.appendCriterion("type like  ", "%" + sSearch + "%");
		}
		// 排序
		int iSortingCols = Integer.parseInt(paramMap.get("iSortingCols"));
		for (int i = 0; i < iSortingCols; i++) {
			String iSortCol = paramMap.get("iSortCol_" + i);
			String mDataProp = paramMap.get("mDataProp_" + iSortCol);
			String sSortDir = paramMap.get("sSortDir_" + i);
			if (i > 0) {
				exp.setOrderByClause(exp.getOrderByClause() + ",");
				exp.setOrderByClause(exp.getOrderByClause() + mDataProp + " "
						+ sSortDir);
			} else {
				exp.setOrderByClause(mDataProp + " " + sSortDir);
			}
		}

		pager = presellService.findAllPresell(pager, exp);

		DataTablesReturnObject<Presell> dtr = new DataTablesReturnObject<Presell>(
				pager.getTotalCount(), paramMap.get("sEcho"), pager.getList());
		return dtr;
	}

	/**
	 * 设置值productTypeValue
	 */
	private void setProductTypeValue2Model(Long productId, Long typeId,
			String productTypeValue, ModelMap model) {
		if (typeId == null) {
			return;
		}

		Map<String, String> fieldValues = new HashMap<>();

		/*
		 * 类型表对应的所有字段
		 */
		List<ProductTypeField> fields = productTypeService
				.findFieldsByTypeId(typeId);
		/*
		 * 对应的值，json格式
		 */
		ProductTypeValue typeValue = productTypeService
				.findProductTypeValueByProductId(productId);
		if (typeValue != null) {
			JSONObject jsonObject = JSONObject
					.parseObject(typeValue.getValue());
			for (int i = 0; fields != null && i < fields.size(); i++) {
				String key = fields.get(i).getCode();
				String value = (String) jsonObject.get(key);

				fieldValues.put(key, value);
			}
		}

		model.put("productTypeFieldValue", fieldValues);
		model.put("productTypeFields", fields);
	}

}
